/*
常用函函数库;
*/
function $1(s){return document.getElementById(s);}
function IsEmpty(s){ return ((s==null) || (s.length==0) ) }
//金额叛断
function chk_money(v){
	a = /^-?\d+(\.\d{2})?$/;

	if(!a.test(v)){
		//alert("须输入正确的金额格式，小数点后不能超过两位")
		return false;
	}
	return true;
}
function chk_isint(val){
  if (val == "")
  {
    return false;
  }
  var reg = /\D+/;
  return !reg.test(val);
}

function getDate(){	    
	this.dateStr=function(){
		var objDate=arguments[0];
		strFormat=arguments[1];
 		if(objDate==undefined||objDate==""||objDate==null){
		  objDate=new Date(); 		  
		}else{
          var a=objDate.split("-")
		  objDate=new Date(a[0],a[1],a[2]);
		}
       
		var W=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
		var WZ=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
		var w=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
		var wz=["日","一","二","三","四","五","六"];
		var M=["January","February","March","April","May","June","July","August","Sebtember","October","November","December"];
		MZ=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];
		var m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Seb","Oct","Nov","Dec"];		
		
		if(!strFormat) strFormat="yyyy-mm-dd HH:MM:SS";		
		var strYear=objDate.getFullYear();
		var strMonth=objDate.getMonth()+1;
		var strDate=objDate.getDate();
		var strHours=azero(objDate.getHours(),2);
		var strMinutes=azero(objDate.getMinutes(),2);
		var strSeconds=azero(objDate.getSeconds(),2);
		var strWeeks=objDate.getDay()+1;
		var strMilliSeconds=objDate.getMilliseconds();
		var strMS=objDate.getTime();
		var strZone=objDate.getTimezoneOffset();
		if(strZone==0){
			strZone="Z";
		}else{
			strZone = Math.abs(Math.round(strZone/60));
			strZone = (objDate.getTimezoneOffset() <0 ? "+":"-") + (strZone<10 ? "0"+strZone : strZone);
		}
		
		strFormat=strFormat.replace(/yyyy/g,strYear);
		strFormat=strFormat.replace(/YY/g,String(strYear).substr(2,4));
		strFormat=strFormat.replace(/mm/g,fz(strMonth));
		strFormat=strFormat.replace(/ME/g,M[Number(strMonth)-1]);
		strFormat=strFormat.replace(/MZ/g,MZ[Number(strMonth)-1]);
		strFormat=strFormat.replace(/me/g,m[Number(strMonth)-1]);
		strFormat=strFormat.replace(/dd/g,fz(strDate));
		strFormat=strFormat.replace(/HH/g,strHours);
		strFormat=strFormat.replace(/MM/g,strMinutes);
		strFormat=strFormat.replace(/SS/g,strSeconds);
		strFormat=strFormat.replace(/ww/g,strWeeks);
		strFormat=strFormat.replace(/WE/g,W[Number(strWeeks)-1]);
		strFormat=strFormat.replace(/WZ/g,WZ[Number(strWeeks)-1]);
		strFormat=strFormat.replace(/we/g,w[Number(strWeeks)-1]);
		strFormat=strFormat.replace(/wz/g,wz[Number(strWeeks)-1]);
		strFormat=strFormat.replace(/MS/g,strMilliSeconds);
		strFormat=strFormat.replace(/ms/g,strMS);
		strFormat=strFormat.replace(/Z/g,strZone+"00");		
		return strFormat;		
	};
    this.checkInt=function(intStr){		
		if(!intStr) return 0;
		intStr=Number(intStr);
		if(isNaN(intStr)) return 0;
		return intStr;
	}
	//enample: 2006-4-8 20:12:34
	this.getDate=function(strDateTime){
		var theDate=new Date();
		var iNum=0;
		var strDate;
		var strTime;

		strDateTime=strDateTime.split(" ");
		if(strDateTime.length==2){
			strDate=strDateTime[0];
			strTime=strDateTime[1];
		}else if(strDateTime.length=1){
			strDate=strDateTime[0];
			strTime="";
		}else{
			return null;
		}

		strDate=strDate.split("-");
		if(strDate.length!=3){
			return null;
		}else{
			theDate.setFullYear(this.checkInt(strDate[0]));
			theDate.setMonth(this.checkInt(strDate[1])-1);
			theDate.setDate(this.checkInt(strDate[2]));
		}

		strTime=strTime.split(":");
		if(strTime.length==3){
			theDate.setHours(this.checkInt(strTime[0]));
			theDate.setMinutes(this.checkInt(strTime[1]));
			theDate.setSeconds(this.checkInt(strTime[2]));
		}		
		return theDate;
	};
}

function czero(a){
	return (a==0||a==null||a=="undefined"||isNaN(a))?"":a;
}

function fz(s){
	return ("00"+s).right(2)
}
//补零函数;
function azero(nRaw,b){  
      var  strNum=nRaw+""   
      var  nCount=b-strNum.length    
      for(var i=1;i<=nCount;i++){  
      strNum="0"+strNum  
      }  
      return   strNum  
}  
//使下拉框选中
function SetSelcted(obj,val){
	 
	$("input[name='"+obj+"']").each(function(){
              alert($(this).val())
			if($(this).val()==val){
				$(this).attr("selected",true);
				//break;
			}
	})	
}
//得到选择项的值;
function getKey(){
	//selkey 当前key序号;selkeyvalue 当前key 值:
	//allkey 所有选中key序号；allkeyvalue 所有选中key 值;
	try{
		var o={selkey:0,
		       allkey:[],
			   selkeyvalue:0,
			   allkeyvalue:[]
		};		 
		$("input[name='keyid']").each(function(i,n){
				if($(this).attr("checked")){
					o.allkey.push(i);
					o.allkeyvalue.push( unescape($(n).val()) );
				}
				if(i==mygrid.selIndex){
					o.selkey=i;
					o.selkeyvalue=unescape($(n).val());
				}
		})	
		return o;
	
	}catch(e){alert(e)}
	 finally{		
		o=null;
	} 
}

//系统重新登录
function relog(x){
	try{		 
		parent.relog(x);
	}catch(e){		 
		parent.relogin(x)
	}
}
//消息提示;
function msgs(x){	
	try{
		if(typeof parent.msgs=="Function"){
			parent.msgs(x)
		}else{
			parent.status(x)
		};
	}catch(e){
		//alert(e)	
	}
}



/*
url:默认以本页为基本url;
act:动作函名;table:表名;
type:0,为获取一个值,1为获取多个值;
id:为id值;
kid：为字段对应的关键字;
ajax :为是否为ajax 操作;
callback:返回类型;
此函数主要是针对GridData进行操作的；
*/
function CAct(o){
	var key=getKey();	
	var obj={	
		url:PI.SELF+PI.query,
		act:null,
		table:null,			
		id:null,
		keyid:'id',
		callback:function(a,e){
			switch(a){
				case 0:
					OpenWin(e)
					break;
				case 1:
					//左边打开;
					lefturl(e)					
				    break;
				case 2:
					alert(e);
					window.location=location;
				    break;
				case 3:
					//刷新本页;	
				 
					window.location=location;
					break;
				case 4:
					//刷新本页;		
				 
					 OpenDivWin('',url);
					break;
				case 5:
					//新窗口打开;		
				    window.open(url);					 
					break;
				default:					
					if(typeof a=="function"){
				         a();
				    }else{
						OpenWin(e)
					}
					break;
			}
		}
	}
	$M.Extend(obj,o);
	if(obj.id){
		o.say=1
	}else{
		if(o.type==-1){
			 var id=key.selkeyvalue;
			 o.say=1;		 
			// o.l=key.allkeyvalue.length;
			if(id==0){alert('请选择一项进行操作');return false;}
			 obj.id=id;		 
		}
		else if(o.type==0){
			 var id=key.selkeyvalue;
			 o.say=1;
			 o.l=key.allkeyvalue.length;
			 if(o.l!=1){alert('请选择一项进行操作');return false;}
			 obj.id=id;	
		}else if(o.type==1){
			 id=(key.allkeyvalue).join(',');
			 o.say=key.allkeyvalue.length;
			 if(id==0){alert('请至少选择一项进行操作');return false;}
			 obj.id=id;	
		}	
	}
	var mycallback=obj.callback;
	obj.ajax=obj.type=obj.back=obj.callback=obj.url=null;
	var url=PI.APP+"/"+obj.act;
	obj.act=null;
	 url+="/?";
	for(k in obj){		
		if(obj[k]){
			url+="&"+k+"="+obj[k];
		}
	}
	
	//url=url.replace("&url=","").replace("/act/","/"); 
	// alert(url)
	if(o.sure){
		if(!confirm('确实要进行操作 '+o.say+'条记录吗?')) return false;	
	}
 	if(o.form){
        var s=[];
         if(o.back==0){_blank_=""};
		 if(o.back==1){_blank_=parent.selFrame};

         s.push("<form name=_bb_form id=_bb_form target=_blank_  action="+o.act+" method=post>")
		 obj.act=obj.url=obj.form=null;
		 for(k in obj){		
			if(obj[k]){
				s.push("<input type=text name="+k+" value="+obj[k]+">");
			}
		}
		s.push("</form>");

		$("body").after( s.join("") );
		$("#_bb_form").submit();
	    return false;
	}
	//msg(url);
	if(o.ajax){	
		$.ajax({
					url: url,
					data: '',
					type:"POST" ,
					dataType:'json', 
					success: function(e){								 
							if(typeof o.back=="function"){
								o.back(e.info);
							}else{
								mycallback(o.back,e.info)
							}
							//window.location=location 				 
									 
					}
			});	
	 }else{
		 mycallback(o.back,url)
	 }

}


$M.Webpages=Class.Extend({
	construct:function(s){ 
	   //初始化
	   // 修复在IE的一些版本中通过CSS改变元素背景图片会出现重新请求闪烁现象.
		try{	
		  if( $M.$Browser.msie){        
            document.execCommand("BackgroundImageCache", false, true);       
          }
		}catch(e){};
    },	
	XML:{},
	Url:location.search.substr(1),
	UrlData:function(a){	 
		return  this.Url.request(a)==false?null:this.Url.request(a).toLowerCase();
	},
	loadXML:function(o){
		var This=this;
		var obj={		 
		   filepath:'',
		   callback:function(){},
		   rand:true
		}
		o=$M.Extend(obj,o);
		var doc=null;
		if(document.implementation&&document.implementation.createDocument){  
          doc=document.implementation.createDocument("","",null);  
          doc.addEventListener("load",function(e){this.readyState=4;},false);  
          doc.readyState=4;		  
        }else{  
          var   msxmls=["MSXML2","Microsoft","MSXML","MSXML3"];  
          for(var   i=0;i<msxmls.length;i++)  
              try{
			  doc=new   ActiveXObject(msxmls[i]+'.DomDocument')
			  }catch(e){
			 }
		} 
		// if (o.rand) 
			 o.filepath+=((o.filepath.indexOf("?")!=-1)?"&":"?")+"rand="+Math.random();
		  //alert(o.filepath)
		if($M.$Browser.msie){
				doc.onreadystatechange = function () { 
					if (doc.readyState==4){o.callback(doc)}; 
				} 			 
		 } 	
		doc.async = false;		 
		 var loaded=doc.load(o.filepath);
		 if($M.$Browser.mozilla){if(loaded){o.callback(doc);}}
	},
	Config:function(dom,id){
		//var dom=this.XML[uid||this.Cuid];		
		var root = dom.documentElement;  
 		  for(var i=0;i<root.childNodes.length;i++){		 
				   if(root.childNodes[i].nodeType==1){  
						  var   file=root.childNodes[i].getAttribute("id");						  
 						  if(file==id){
							  return root.childNodes[i].childNodes[0].nodeValue.toString();							
						  }
					}
		  }
	}, 
	Configall:function(dom){
		  var o={}
		  var root = dom.documentElement;  
 		  for(var i=0;i<root.childNodes.length;i++){		 
				   if(root.childNodes[i].nodeType==1){  
						  var   file=root.childNodes[i].getAttribute("id");						  
 						   o[file]=root.childNodes[i].childNodes[0].nodeValue.toString();							  						
						  
					}
		  }
		  return   new $M.Mobj(o)	
	}, 	
	debug:function(e){
		alert(e)
	},
	getWebName:function(){
		var webNames= window.location.pathname.split("/")
		var webName=webNames[webNames.length-1].replace(".php","").replace(".html","").toLowerCase()
		if(webName==""){webName="index"}
		return webName;
	},
	getWH:function(){
		var o={}
		try{
			//alert([ document.body.clientHeight,document.documentElement.clientHeight])
		o.height= document.compatMode=="CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight; 
		o.width= document.compatMode=="CSS1Compat" ? document.documentElement.clientWidth : document.body.clientWidth; 
		}catch(e){		
		}
		return o;
		  var o = { };
		  ["Width","Height"].each(function(d) {
				     var s = d.toLowerCase();
				      //var D = d.capitalize();
				      if (isSafari && !document.evaluate) {
				        // Safari <3.0 needs self.innerWidth/Height
				        o[s] = self['inner' + d];
				      } else if (isOpera && parseFloat(window.opera.version()) < 9.5) {
				        // Opera <9.5 needs document.body.clientWidth/Height
				        o[s] = document.body['client' + d]
				      } else {
							 $M.$Browser.isStrict?						
							 o[s] = document.documentElement['client' + d]:
								   document.body['client' + d];
				     }
			 
			});
			return o;		 
	},
	getXY:function(t){		 
			var target = t;
			//alert(target.offsetLeft);
			var pos ={
				x:target.offsetLeft,
				y:target.offsetTop
			} 
			var target = target.offsetParent;	 
			while (target){
				pos.x += target.offsetLeft;
				pos.y += target.offsetTop;
				
				target = target.offsetParent
			}    
			return pos;
	},
	flashshow:function(){
	$("#flashdiv").css({border: "1px dashed  black", width:(this.getWH().width-5)+"px",height:(this.getWH().height-5)+"px",zIndex:99,position:"absolute",background:"#FAFCFD",opacity:0.8,filter:"alpha(opacity=80)",disabled:true, "*margin-top":"-10px",top:"0px"});
 
		$("#flashdiv").fadeIn(3);
		 
	},
	flashhide:function(){		
		$("#flashdiv").fadeOut(3);
		return false;	
	},
	getAjaxData:function(e){	
			 var o={};
			 o.table="";
			 o.act="getall";
			 o.where=" 1=1 ";
			 o.sort="id desc";
			 o.fields="*";
			 o.page="0";
			 o.pagesize="10";
			 o.id=null;
			 o.key=null;			 
			 var url=PI.APP;	
			 url+="/Ajaxdata";			
			 $M.Extend(o,e);
			 o.callback=null;
			 var data=($M.toJSON(o));
			// alert(data);
			 $.ajax({
					url: url,
					data:data,
					type:"POST" ,
					dataType:"json",
					success: function(f){
						if(typeof e.callback=="function"){
							e.callback(f);
						}
					}
				});		
	
	}
})

var thePage=new $M.Webpages();
//得到url的文件名;
function geturlfilename(a){
	
	var b=a.split("/"); 
	var c=b.slice(b.length-1, b.length).toString(String).split("."); 
	return c.slice(0, 1); 

}

function   addOption(objSelectNow,val,txt) {  
  var   objOption   =   document.createElement("OPTION");  
  objOption.text=   txt;  
  objOption.value=val;  
  $1(objSelectNow).options.add(objOption);  
 }

function clearOption(id){
  $1(id).options.length=0;  
}
var Datalist = new Object();
Datalist.query = "query";
Datalist.filter = new Object();
/**
 * 创建一个可编辑区
 */
Datalist.edit = function(obj, act, id){
  var tag = obj.firstChild.tagName;

  if (typeof(tag) != "undefined" && tag.toLowerCase() == "input")
  {
    return;
  }
  /* 保存原始的内容 */
  var org = obj.innerHTML;
  var val = $M.$Browser.msie ? obj.innerText : obj.textContent;

  /* 创建一个输入框 */
  var txt = document.createElement("INPUT");
  txt.value = (val == 'N/A') ? '' : val;
  txt.style.width = (obj.offsetWidth + 12) + "px" ;

  /* 隐藏对象中的内容，并将输入框加入到对象中 */
  obj.innerHTML = "";
  obj.appendChild(txt);
  txt.focus();

  /* 编辑区输入事件处理函数 */
  txt.onkeypress = function(e)
  {
    var evt = Utils.fixEvent(e);
    var obj = Utils.srcElement(e);

    if (evt.keyCode == 13)
    {
      obj.blur();

      return false;
    }

    if (evt.keyCode == 27)
    {
      obj.parentNode.innerHTML = org;
    }
  }

  /* 编辑区失去焦点的处理函数 */
  txt.onblur = function(e){
		if (Utils.trim(txt.value).length > 0){
			var url=PI.APP+"/"+act;	  
			$.ajax({
					url: url,
					data: 'id='+id+'&val=' + encodeURIComponent(Utils.trim(txt.value)),
					type:"POST" ,
					dataType:'json', 
					success: function(s){	
						if (s.message) {
							alert(res.message);
						}
						obj.innerHTML = (s.error == 0) ? s.content : org;						 								 
					}
			});     
		} else{
		  obj.innerHTML = org;
		}
  }

}

/**
 * 切换状态
 */
Datalist.toggle = function(act,id,e){

   var url=PI.APP+"/"+act;
   var src=geturlfilename(e.src);
	$.ajax({
					url: url,
					data: 'id='+id,
					type:"POST" ,
					dataType:'json', 
					success: function(s){	
						if(s.status==1){
							e.src=(src=='sok')?PI.public+'/Images/sno.gif':PI.public+'/Images/sok.gif'; 
						}
						alert(s.info)									 
					}
	});

}

/**
 * 切换排序方式
 */
Datalist.sort = function(sort_by, sort_order)
{
  var args = "act="+this.query+"&sort_by="+sort_by+"&sort_order=";

  if (this.filter.sort_by == sort_by)
  {
    args += this.filter.sort_order == "DESC" ? "ASC" : "DESC";
  }
  else
  {
    args += "DESC";
  }

  for (var i in this.filter)
  {
    if (typeof(this.filter[i]) != "function" &&
      i != "sort_order" && i != "sort_by" && !Utils.isEmpty(this.filter[i]))
    {
      args += "&" + i + "=" + this.filter[i];
    }
  }

  this.filter['page_size'] = this.getPageSize();

  Ajax.call(this.url, args, this.listCallback, "POST", "JSON");
}

/**
 * 翻页
 */
Datalist.gotoPage = function(page)
{

  if (page != null) this.filter['page'] = page;

  if (this.filter['page'] > this.pageCount) this.filter['page'] = 1;
//alert(Datalist.getPageSize())
  this.filter['page_size'] = this.getPageSize();

  this.loadList();
}

/**
 * 载入列表
 */
Datalist.loadList = function()
{
	
   var args =  this.compileFilter()+"&menuid="+PI.menuid;
   var url=Datalist.url+"/query/";
  
	$.ajax({
					url: url,
					data: args,
					type:"POST" ,
					dataType:'json', 
					success: function(s){	
						Datalist.listCallback(s)						 
					}
	});
 // Ajax.call(this.url, args, this.listCallback, "POST", "JSON");
}

/**
 * 删除列表中的一个记录
 */
Datalist.remove = function(id, cfm, opt)
{
  if (opt == null)
  {
    opt = "remove";
  }

  if (confirm(cfm))
  {
    var args = "id=" + id + this.compileFilter();
    var url=PI.APP+"/"+opt;

	$.ajax({
						url: url,
						data: args,
						type:"POST" ,
						dataType:'json', 
						success: function(s){	
							Datalist.listCallback (s)								 
						}
		});   
  }

}

Datalist.gotoPageFirst = function()
{
	dump(this.filter)
  if (this.filter.page > 1)
  {
    Datalist.gotoPage(1);
  }
}

Datalist.gotoPagePrev = function()
{
  if (this.filter.page > 1)
  {
    Datalist.gotoPage(this.filter.page - 1);
  }
}

Datalist.gotoPageNext = function()
{
  if (this.filter.page < Datalist.pageCount)
  {
    Datalist.gotoPage(parseInt(this.filter.page) + 1);
  }
}

Datalist.gotoPageLast = function()
{
  if (this.filter.page < Datalist.pageCount)
  {
    Datalist.gotoPage(Datalist.pageCount);
  }
}

Datalist.changePageSize = function(e)
{
    var evt = Utils.fixEvent(e);
    if (evt.keyCode == 13)
    {
        Datalist.gotoPage();
        return false;
    };
}

Datalist.listCallback = function(result, txt)
{
  if (result.error > 0)
  {
    alert(result.message);
  }
  else
  {
    try
    {
		//alert(result.content);
      document.getElementById('listDiv').innerHTML = result.content;

      if (typeof result.filter == "object")
      {
        Datalist.filter = result.filter;
      }

      Datalist.pageCount = result.page_count;
    }
    catch (e)
    {
      alert(e.message);
    }
  }
}

Datalist.selectAll = function(obj, chk)
{
  if (chk == null)
  {
    chk = 'checkboxes';
  }

  var elems = obj.form.getElementsByTagName("INPUT");

  for (var i=0; i < elems.length; i++)
  {
    if (elems[i].name == chk || elems[i].name == chk + "[]")
    {
      elems[i].checked = obj.checked;
    }
  }
}

Datalist.compileFilter = function()
{
  var args = '';
  for (var i in this.filter)
  {
    if (typeof(this.filter[i]) != "function" && typeof(this.filter[i]) != "undefined")
    {
      args += "&" + i + "=" + encodeURIComponent(this.filter[i]);
    }
  }

  return args;
}

Datalist.getPageSize = function()
{
  var ps = 15;

  pageSize = $("#pageSize").val();

  if (pageSize)
  {
	
    ps = chk_isint(pageSize) ? pageSize: 15;  
    document.cookie = "MDL[page_size]=" + ps + ";";
	$M.Cookies.set("MDL[page_size]",ps);

  }
}

Datalist.addRow = function(checkFunc)
{
  cleanWhitespace(document.getElementById("listDiv"));
  var table = document.getElementById("listDiv").childNodes[0];
  var firstRow = table.rows[0];
  var newRow = table.insertRow(-1);
  newRow.align = "center";
  var items = new Object();
  for(var i=0; i < firstRow.cells.length;i++) {
    var cel = firstRow.cells[i];
    var celName = cel.getAttribute("name");
    var newCel = newRow.insertCell(-1);
    if (!cel.getAttribute("ReadOnly") && cel.getAttribute("Type")=="TextBox")
    {
      items[celName] = document.createElement("input");
      items[celName].type  = "text";
      items[celName].style.width = "50px";
      items[celName].onkeypress = function(e)
      {
        var evt = Utils.fixEvent(e);
        var obj = Utils.srcElement(e);

        if (evt.keyCode == 13)
        {
          Datalist.saveFunc();
        }
      }
      newCel.appendChild(items[celName]);
    }
    if (cel.getAttribute("Type") == "Button")
    {
      var saveBtn   = document.createElement("input");
      saveBtn.type  = "image";
      saveBtn.src = "./images/icon_add.gif";
      saveBtn.value = save;
      newCel.appendChild(saveBtn);
      this.saveFunc = function()
      {
        if (checkFunc)
        {
          if (!checkFunc(items))
          {
            return false;
          }
        }
        var str = "act=add";
        for(var key in items)
        {
          if (typeof(items[key]) != "function")
          {
            str += "&" + key + "=" + items[key].value;
          }
        }
        res = Ajax.call(Datalist.url, str, null, "POST", "JSON", false);
        if (res.error)
        {
          alert(res.message);
          table.deleteRow(table.rows.length-1);
          items = null;
        }
        else
        {
          document.getElementById("listDiv").innerHTML = res.content;
          if (document.getElementById("listDiv").childNodes[0].rows.length < 6)
          {
             Datalist.addRow(checkFunc);
          }
          items = null;
        }
      }
      saveBtn.onclick = this.saveFunc;

      //var delBtn   = document.createElement("input");
      //delBtn.type  = "image";
      //delBtn.src = "./images/no.gif";
      //delBtn.value = cancel;
      //newCel.appendChild(delBtn);
    }
  }

}

window.onerror = function(){

}; 
